
const fs = require('fs');
const path = require('path');
const userShareService = require('./userShareService');

/**
 * 规则服务器，按照 whistle 官方文档规范实现
 * 这个函数会被 whistle 调用，用于获取插件提供的规则
 * 
 * @param {Object} server - whistle 提供的 server 对象
 * @param {Object} options - whistle 提供的配置对象
 */
module.exports = (server, options) => {
  console.log('[NoHost] 初始化 Rules Server (实时同步模式)');
  
  try {
    // 注册请求处理函数
    server.on('request', async (req, res) => {
      try {
        console.log('[NoHost] RulesServer 收到规则请求 - 实时获取最新状态');
        
        // 实时生成当前激活环境的规则
        const rules = await generateActiveRules();
        
        console.log('[NoHost] 实时生成的规则:', rules);
        
        // 设置强制无缓存响应头
        res.setHeader('Content-Type', 'text/plain; charset=utf-8');
        res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
        res.setHeader('Pragma', 'no-cache');
        res.setHeader('Expires', '0');
        res.setHeader('X-NoHost-Timestamp', new Date().toISOString());
        res.setHeader('X-NoHost-Shared-Data', 'enabled');
        
        // 返回规则文本 - whistle 会解析这些规则并应用
        res.end(rules);
        
      } catch (error) {
        console.error('[NoHost] RulesServer 错误:', error);
        res.statusCode = 500;
        res.end('# NoHost Rules Server Error\n');
      }
    });
  } catch (error) {
    console.error('[NoHost] RulesServer 初始化失败:', error);
  }
};

/**
 * 生成当前激活环境的所有规则
 */
async function generateActiveRules() {
  const rules = [];

  // 添加规则头部注释
  rules.push('# NoHost Plugin Rules');
  rules.push('# Generated at: ' + new Date().toISOString());
  rules.push('');

  try {
    // 获取合并后的数据（包含本地和共享数据）
    const data = await userShareService.getMergedData(true);
    
    // 添加共享数据标记
    rules.push('# Including shared projects from other users');
    rules.push('');
    
    // 如果获取失败，尝试直接读取本地文件
    if (!data || (!data.projects && !data.projectGroups)) {
      console.warn('[NoHost] 获取合并数据失败，尝试读取本地数据');
      
      // 直接读取 project.json 文件
      const dataFilePath = path.join(__dirname, '../public/project.json');
      let localData = { projects: [] };
      
      if (fs.existsSync(dataFilePath)) {
        try {
          const fileContent = fs.readFileSync(dataFilePath, 'utf8');
          localData = JSON.parse(fileContent);
          return generateRulesFromData(localData, rules);
        } catch (error) {
          console.error('[NoHost] 读取 project.json 失败:', error);
          return rules.join('\n');
        }
      }
    }

    return generateRulesFromData(data, rules);
  } catch (error) {
    console.error('[NoHost] 生成规则失败:', error);
    rules.push('# Error generating rules: ' + error.message);
    return rules.join('\n');
  }
}

/**
 * 从数据对象生成规则
 * @param {Object} data 数据对象
 * @param {Array} rules 初始规则数组
 * @returns {string} 生成的规则文本
 */
function generateRulesFromData(data, rules = []) {
  // 获取所有激活的环境
  const activeEnvironments = [];
  if (data.projects && Array.isArray(data.projects)) {
    data.projects.forEach(project => {
      if (project.environments && Array.isArray(project.environments)) {
        project.environments.forEach(env => {
          if (env.isActive) {
            activeEnvironments.push({
              projectId: project.id,
              projectName: project.name,
              envId: env.id,
              envName: env.name,
              envType: env.type,
              hosts: env.hosts,
              isActive: env.isActive,
              isShared: project.isShared || false // 标记是否为共享项目
            });
          }
        });
      }
    });
  }

  console.log('[NoHost] 激活的环境:', activeEnvironments);

  if (activeEnvironments.length === 0) {
    rules.push('# No active environments');
    return rules.join('\n');
  }

  // 添加通用调试信息
  rules.push('# === NoHost Plugin Active Environments ===');
  rules.push(`# Total active environments: ${activeEnvironments.length}`);
  rules.push('');

  // 为每个激活的环境生成规则
  activeEnvironments.forEach(env => {
    rules.push('');
    rules.push(`# === Project: ${env.projectName}${env.isShared ? ' (Shared)' : ''} ===`);
    rules.push(`# Environment: ${env.envName} (${env.envType})`);
    rules.push(`# Project ID: ${env.projectId}`);
    rules.push(`# Environment ID: ${env.envId}`);
    rules.push(`# Activation time: ${new Date().toISOString()}`);
    rules.push('');

    if (env.hosts && env.hosts.length > 0) {
      rules.push('# Host rules:');
      env.hosts.forEach(hostConfig => {
        if (hostConfig && hostConfig.trim()) {
          const rule = parseHostConfig(hostConfig);
          if (rule) {
            rules.push(rule);
          }
        }
      });
    } else {
      rules.push(`# ${env.projectName} - ${env.envName}: No configuration`);
    }

    // 添加一个调试头，便于验证规则是否生效
    rules.push(`# Add debug header for ${env.projectName}`);
    rules.push(`* reqHeaders://x-nohost-active-env=${env.projectName}-${env.envName}${env.isShared ? '-shared' : ''}`);
    rules.push('');
  });

  return rules.join('\n');
}

/**
 * 解析host配置为whistle规则格式
 * 输入: "127.0.0.1:8181 dgvip360.drivergenius3.com"
 * 输出: "dgvip360.drivergenius3.com 127.0.0.1:8181"
 */
function parseHostConfig(hostConfig) {
  if (!hostConfig || typeof hostConfig !== 'string') {
    return '';
  }

  const parts = hostConfig.trim().split(/\s+/);
  if (parts.length >= 2) {
    const proxy = parts[0]; // 127.0.0.1:8181
    const domain = parts[1]; // dgvip360.drivergenius3.com
    return `${domain} ${proxy}`;
  }

  return '';
}


